import { api } from "@/global/utils/api"
import useApiPromiseHandler from "./api-promise-handler"
import { ref, computed } from "vue";

export default function useImageUploader(t, dir) {
  const postFileList = ref([]);

  const postFileUrls = computed(() => {
    let list = [];
    postFileList.value.forEach(f => {
      if (f.response) {
        f.response.data.forEach(e => list.push(e));
      }
    });
    return list;
  });

  const uploadImage = (requestObj) => {
    const param = new FormData();
    param.append("images", requestObj.file);
    const config = {
      headers: { "Content-Type": "multipart/form-data" }
    };
    useApiPromiseHandler(t,
      api.post(`/images/upload/${dir}`, param, config),
      requestObj.onSuccess,
      requestObj.onError
    );
  };

  const removeImage = (file) => new Promise((resolve, reject) => {
    if (!file || !file.response || !file.response.data) {
      resolve('');
      return;
    }
    const serverUrl = file.response.data[0];
    const filename = serverUrl.substring(serverUrl.lastIndexOf('/') + 1);
    useApiPromiseHandler(t, 
      api.get(`/images/delete/${dir}/${filename}`),
      resolve,
      reject
    );
  });
  
  return { uploadImage, removeImage, postFileList, postFileUrls };
}